<?php
/**
 * 产品模块
 *
 * 产品service
 *
 * @author zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\ProductsService;
use App\Services\BaseService;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\UserService\UserTool;
use App\Services\PreferentialService\PreferentialService;
use App\Services\ProductsService\ProductTrait\product_trait;
use App\Services\GiftService\GiftApiService;
use App\Services\ColourService\ColourTool;
use App\Services\FavoritesService\FavoritesService;
use App\Services\UserCollectionsService\UserCollectionsService;
use App\Services\ProductsService\ProductsCreateService;
use App\Services\Tool\GeneralTool;
use App\Jobs\Php2PyImg;
use Illuminate\Support\Facades\Queue;
use App\Services\ProductsService\ProductTool;
use App\Services\SourcePicService\SourcePicTool;
use App\Services\Tool\Car\CarTool;
use App\Services\Exceptions\PriceErrorException;
use App\Services\ImgServices\ImgTool;
use App\Services\Tool\ImageProcessor\ImagickTool;
use App\Model\Announcements;
use DB;
use Log;
class ProductsService extends BaseService
{
    use product_trait;
    protected $userTool;
    protected $imagick_tool;
    protected $product_temp_tool;
    protected $favorites_service;
    protected $products_create_service;
    protected $user_collections_service;
    const IMAGE_TEMPORARY_STORAGE_PATH = 'product_temporary_storage_images/';
    const IMAGE_PATH = 'product_images/';
    const DRAFT_IMAGE_PATH = 'product_draft_images/';
    const PREFIX_PATH = '/images/';
    public function __construct(UserTool $userTool, ProductTempTool $product_temp_tool, FavoritesService $favorites_service,
                                ProductsCreateService $products_create_service,UserCollectionsService $user_collections_service,
                                ProductTool $product_tool,CarTool $car_tool,ImagickTool $imagick_tool, SourcePicTool $source_pic_tool)
    {
        $this->userTool = $userTool;
        $this->product_temp_tool = $product_temp_tool;
        $this->favorites_service = $favorites_service;
        $this->products_create_service = $products_create_service;
        $this->user_collections_service = $user_collections_service;
        $this->product_tool = $product_tool;
        $this->car_tool = $car_tool;
        $this->imagick_tool = $imagick_tool;
        $this->source_pic_tool = $source_pic_tool;
    }
    /**
     * 获取所有作品
     * @param $per_page
     * @param $sort
     * @return array
     */
    public function getList($product_temp_category_id, $per_page = 10, $order = 'created_at', $sort = 'desc', $conditions = array(),$user_id=0)
    {
        $this->table = 'products';
        $this->where = [['is_shelves', '=', 1], ['state', '=', 1], ['is_show','=',1]];
        $this->select = [
            'product_id', 'user_id', 'colour_id', 'product_temp_id',
            'overflow_price', 'title', 'description', 'dig_num', 'collect_num',
            'price as original_price','preferential_price'
        ];
        $this->order = $order;
        $this->sort = $sort;
        if (!empty($conditions)) {
            //查询
            $conditions_arr = array();
            $conditions_price_arr = array();
            foreach ($conditions as $condition) {
                if ($condition->type == 1) {
                    //查询价格
                    $condition_price_arr['type'] = $condition->type;
                    $condition_price_arr['search_condition'] = $condition->search_condition;
                    $conditions_price_arr[] = $condition_price_arr;
                } else {
                    $condition_arr['type'] = $condition->type;
                    $condition_arr['search_condition'] = $condition->search_condition;
                    $conditions_arr[] = $condition_arr;
                }
            }
            if(empty($conditions_arr) && empty($conditions_price_arr)){
                $result = array('last_page' => 0, 'per_page' => $per_page, 'current_page' => 1, 'data' => []);
                return $this->createResult('M00000', $result);
            }
            $products = $this->getListByProductTempCategoryWithCondition($product_temp_category_id, $conditions_arr, $conditions_price_arr, $per_page);
        } else {
            $products = $this->getListByProductTempIds($product_temp_category_id, $per_page);
        }
        $good_settlement_quantity = empty($user_id) ? 0 : $this->car_tool->get_shop_car_quantity(array('user_id'=>$user_id),2)['good_settlement_quantity'];
        $result = array('total_page' => $products['last_page'], 'per_page' => $per_page, 'current_page' => $products['current_page'], 'data' => $products['data'], 'good_settlement_quantity' => $good_settlement_quantity);
        return $this->createResult('M00000', $result);
    }
    /**
     * 获取用户作品列表
     * @param $user_id
     * @param $per_page
     * @return array
     */
    public function get_list_by_user_id($user_id,$per_page){
        try {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(array('user_id', '=', $user_id),array('state', '=', 1)),
                'select' => array('product_id', 'product_temp_id', 'colour_id', 'is_shelves',
                    'overflow_price', 'stock', 'is_infinite_stock', 'off_shelves_time', 'is_infinite_time',
                    'price as original_price', 'preferential_price'
                ),
                'order' => 'updated_at',
                'sort' => 'desc'
            ));
            $products = $this->getAllPaginated($per_page)->toArray();
            foreach ($products['data'] as $product) {
                $product = $this->get_product_preview_images($product);
                //$price_arr = $this->get_customize_price($product);
                //$product->original_price = $price_arr['original_price'];//成本价
                $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
                $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
                $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
                $product->original_price = GeneralTool::priceFormat($product->original_price);
                $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
                $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
            }
            $result = array('total_page' => $products['last_page'], 'per_page' => $per_page, 'current_page' => $products['current_page'], 'data' => $products['data']);
            return $this->createResult('M00000', $result);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M09036', (object)array());
        }
    }
    /**
     * 获取作品集中的作品
     * @param $user_id
     * @param $collection_id
     * @param int $per_page
     * @return array
     */
    public function getProductsByCollectionId($user_id, $collection_id, $type = 'collections', $per_page = 10)
    {
        //获取已上架作品
        try {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(
                    array('user_id', '=', $user_id),
                    array('user_collection_id', '=', $collection_id),
                    array('is_shelves','=',1),
                    array('state', '=', 1)
                ),
                'select' => array('product_id', 'product_temp_id', 'colour_id', 'is_shelves', 'sell_num',
                    'overflow_price', 'stock', 'is_infinite_stock', 'off_shelves_time', 'is_infinite_time',
                    'price as original_price'
                ),
                'order' => 'created_at',
                'sort' => 'desc'
            ));
            $products = $this->getAllPaginated($per_page)->toArray();
            foreach ($products['data'] as $key => $product) {
                //判断下架状态
                if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                    $product->is_shelves = 0;
                    //剔除超出下架时间商品
                    array_splice($products['data'],$key,1);
                    continue;
                }
                $product = $this->get_product_preview_images($product);
                //$price_arr = $this->get_customize_price($product);
                $product->original_price = GeneralTool::priceFormat(bcsub($product->original_price,$product->overflow_price,2));//成本价
                //新增名称
                $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
                $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
                $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
            }
            $result = array('total_page' => $products['last_page'], 'per_page' => $per_page, 'current_page' => $products['current_page'], 'data' => $products['data']);
            return $this->createResult('M00000', $result);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M09036', (object)array());
        }
    }

    /**
     * 获取已上架商品
     * @param $user_id
     * @param int $per_page
     */
    public function get_shelves_products($user_id, $per_page = 10)
    {
        try {
            $this->setParameter(array(
                'table' => 'products',
                'where' => array(
                    array('user_id', '=', $user_id),
                    array('is_shelves', '=', 1),
                    array('state', '=', 1)
                ),
                'select' => array('product_id', 'product_temp_id', 'colour_id', 'is_shelves', 'sell_num',
                    'overflow_price', 'stock', 'is_infinite_stock', 'off_shelves_time', 'is_infinite_time'),
                'order' => 'created_at',
                'sort' => 'desc'
            ));
            $products = $this->getAllPaginated($per_page)->toArray();
            foreach ($products['data'] as $key=>$product) {
                if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                    $product->is_shelves = 0;
                    unset($products['data'][$key]);
                }
                $product = $this->get_product_preview_images($product);
                //$price_arr = $this->get_customize_price($product);
                //$product->original_price = GeneralTool::priceFormat(bcsub($product->original_price,$product->overflow_price,2));//成本价
                $product_temp_name = $this->product_temp_tool->getProductTempNameByProductTempId($product->product_temp_id);
                $product->product_temp_name = isset($product_temp_name) ? $product_temp_name : '';

            }
            $result = array('total_page' => $products['last_page'], 'per_page' => $per_page, 'current_page' => $products['current_page'], 'data' => $products['data']);
            return $this->createResult('M00000', $result);
        }catch (\Exception $e){
            Log::info($e);
            return $this->createResult('M09036', (object)array());
        }
    }

    /**
     * 获取已下架商品
     * @param $user_id
     * @param int $per_page
     */
    public function get_out_shelves_products($user_id, $per_page = 10)
    {
        try {
            $products = DB::table('products')
                ->where([
                    ['is_shelves','=',0],
                    ['user_id','=',$user_id],
                    ['state','=',1]
                ])
                ->orWhere([
                    ['is_shelves','=',1],
                    ['user_id','=',$user_id],
                    ['state','=',1],
                    ['is_infinite_time','=',0],
                    ['off_shelves_time','<',time()]
                ])
                ->select('product_id', 'product_temp_id', 'colour_id', 'is_shelves', 'sell_num',
                    'overflow_price', 'stock', 'is_infinite_stock', 'off_shelves_time', 'is_infinite_time')
                ->orderBy('created_at','desc')
                ->paginate($per_page)
                ->toArray();
            foreach ($products['data'] as $key=>$product) {
                if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                    $product->is_shelves = 0;
                    //unset($products['data'][$key]);
                }
                $product = $this->get_product_preview_images($product);
                //$price_arr = $this->get_customize_price($product);
                //$product->original_price = GeneralTool::priceFormat(bcsub($product->original_price,$product->overflow_price,2));//成本价
                $product_temp_name = $this->product_temp_tool->getProductTempNameByProductTempId($product->product_temp_id);
                $product->product_temp_name = isset($product_temp_name) ? $product_temp_name : '';

            }
            $result = array('total_page' => $products['last_page'], 'per_page' => $per_page, 'current_page' => $products['current_page'], 'data' => $products['data']);
            return $this->createResult('M00000', $result);
        }catch (\Exception $e){
            Log::info($e);
            return $this->createResult('M09036', (object)array());
        }
    }

    /**
     * 根据条件获取产品
     */
    public function getListByProductTempCategoryWithCondition($product_temp_category_id,$conditions_arr = array(), $conditions_price_arr = array(),$per_page=10){
        if (count($conditions_price_arr) > 0) {
            //查询价格是否满足
            $search_condition = $conditions_price_arr[0]['search_condition'];//只能单选
            if (!empty($search_condition)) {
                $search_condition_arr = explode('-', $search_condition[0]);
                if (is_array($search_condition_arr) && count($search_condition_arr) > 1) {
                    $this->where[] = ['preferential_price', '>=', $search_condition_arr[0]];
                    $this->where[] = ['preferential_price', '<=', $search_condition_arr[1]];
                }
            }
        }
        //根据$product_temp_ids获取所有的作品
        if(empty($conditions_arr)){
            //直接筛选价格满足的
            if($product_temp_category_id == 0){
                //查全部
                $products = $this->getAllPaginated($per_page)->toArray();
            }else{
                $product_temp_ids = ProductTempTool::getProdTempIdsByCategoryId($product_temp_category_id);
                $this->whereIn = $product_temp_ids;
                $products = $this->getAllByResourceIdsPaginated('product_temp_id', $per_page)->toArray();
            }
        }else{
            foreach($conditions_arr as $item){
                if($item['type'] == 4){
                    //颜色
                    $product_ids_by_color = DB::table('products')->where([['is_shelves', '=', 1], ['state', '=', 1]])->whereIn('colour_id',$item['search_condition'])->pluck('product_id')->toArray();
                }
                continue;
            }
            $product_temp_ids = ProductTempTool::getProdTempIds($conditions_arr, $product_temp_category_id);
            $query = DB::table('products')->where($this->where)->whereIn('product_temp_id',$product_temp_ids);
            if(isset($product_ids_by_color)){
                $query->whereIn('product_id',$product_ids_by_color);
            }
            //$this->whereIn = $product_temp_ids;
            $products = $query->select($this->select)->orderBy($this->order,$this->sort)->paginate($per_page)->toArray();
            //$products = $this->getAllByResourceIdsPaginated('product_temp_id', $per_page)->toArray();
        }
        foreach ($products['data'] as $product) {
            try{
                $this->get_product_base_parameter($product);
            }catch (PriceErrorException $e){
                Log::info($e);
                array_splice($products['data'],$key,1);
            }
        }
        return $products;
    }
    /**
     * 根据product_temp_category_id获取产品
     * @param $product_temp_category_id
     * @param $per_page
     * @return mixed
     */
    public function getListByProductTempIds($product_temp_category_id, $per_page)
    {
        if ($product_temp_category_id == 0) {
            //获取全部
            $products = $this->getAllPaginated($per_page)->toArray();
        } else {
            //根据$product_temp_category_id获取该分类下所有的product_temp_id
            //type=1为普通搜索 type=2 为自定义搜索
            $product_temp_ids = ProductTempTool::getProdTempIdsByCategoryId($product_temp_category_id);
            $this->whereIn = $product_temp_ids;
            $products = $this->getAllByResourceIdsPaginated('product_temp_id', $per_page)->toArray();
        }
        foreach ($products['data'] as $product) {
            try{
                $this->get_product_base_parameter($product);
            }catch (PriceErrorException $e){
                Log::info($e);
                array_splice($products['data'],$key,1);
            }
        }
        return $products;
    }
    /**
     * 获取产品的基本参数（如有异常产品，提出，不影响整体）
     */
    private function get_product_base_parameter($product)
    {
        $product = $this->get_product_preview_images($product);
        $user = $this->userTool->userInfoByid($product->user_id);
        $product->nick_name = $user->nick_name;
        $product->avatar = $user->avatar;
        //获取是否有赠品
        $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
        foreach($product->gift as $key=>$gift){
            $gift->quantity = $gift->num;
        }
//        $price_arr = $this->getTotalPrice($product);
        $product->original_price = GeneralTool::priceFormat($product->original_price);
        $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
        $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
    }
    /**
     * 根据一组资源ID获取产品列表
     * @param $resource_ids
     * @return array
     */
    public function getListByReSourceIds($resource_ids)
    {
        try {
            //排序通过order控制
            $this->table = 'products';
            $this->select = [
                'product_id', 'user_id', 'colour_id', 'product_temp_id',
                'overflow_price', 'title', 'description', 'dig_num', 'collect_num',
                'price as original_price','preferential_price','stock','is_infinite_stock'
            ];
            $products = array();
            foreach ($resource_ids as $resource_id) {
                $this->where = [['product_id', '=', $resource_id->resource_id], ['is_shelves', '=', 1], ['is_show','=',1], ['state', '=', 1]];
                $product = $this->getById();
                if (!empty($product)) {
                    $product = $this->get_product_preview_images($product);
                    $user = $this->userTool->userInfoByid($product->user_id);
                    $product->nick_name = $user->nick_name;
                    $product->avatar = $user->avatar;
                    //获取是否有赠品
                    $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
                    foreach($product->gift as $key=>$gift){
                        $gift->quantity = $gift->num;
                    }
                    //$price_arr = $this->getTotalPrice($product);
                    $product->original_price = GeneralTool::priceFormat($product->original_price);
                    $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
                    $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
                    $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
                    $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
                    $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
                    $products[] = $product;
                }
            }
            return $products;
        } catch (\Exception $e) {
            Log::info($e);
            return array();
        }
    }
    /**
     * 根据一组资源ID获取产品列表
     * @param $resource_ids
     * @return array
     */
    public function get_list_over_resources_ids($resource_ids,$per_page=10)
    {
        try {
            //排序通过order控制
            $this->table = 'products';
            $this->select = [
                'product_id', 'user_id', 'colour_id', 'product_temp_id',
                'overflow_price', 'title', 'description', 'dig_num', 'collect_num',
                'price as original_price','preferential_price'
            ];
            $this->where = [['is_shelves', '=', 1], ['state', '=', 1]];
            $this->whereIn = $resource_ids;
            $this->order = 'updated_at';
            $this->sort = 'desc';
            $products = $this->getAllByResourceIdsPaginated('product_id',$per_page);
            foreach($products as $product){
                $product = $this->get_product_preview_images($product);
                $user = $this->userTool->userInfoByid($product->user_id);
                $product->nick_name = $user->nick_name;
                $product->avatar = $user->avatar;
                //获取是否有赠品
                $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
                foreach($product->gift as $key=>$gift){
                    $gift->quantity = $gift->num;
                }
                //$price_arr = $this->getTotalPrice($product);
                $product->original_price = GeneralTool::priceFormat($product->original_price);
                $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
                $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
            }
            return $products;
        } catch (\Exception $e) {
            Log::info($e);
            return array();
        }
    }

    /**
     * 获取修改产品的详情
     * @param $user_id
     * @param $product_id
     */
    public function getModifyProduct($user_id,$product_id){
        $this->setParameter([
            'table' => 'products',
            'where' => [
                ['user_id','=',$user_id],
                ['product_id','=',$product_id],
                ['state','=',1]
            ],
            'select' => array('product_id', 'user_collection_id', 'product_temp_id', 'colour_id', 'is_shelves', 'overflow_price',
                'price as original_price', 'preferential_price', 'stock', 'is_infinite_stock', 'off_shelves_time', 'is_infinite_time')
        ]);
        $product = $this->getById();
        if(empty($product)){
            return $this->createResult('M08001',(object)array());
        }
        //获取作品集
        $collection = $this->user_collections_service->get_collection_by_user_id_collection_id($user_id,$product->user_collection_id);
        if(empty($collection)){
            //获取默认作品集
            $collection = DB::table('user_collections')->where([['user_id', '=', $user_id], ['is_default', '=', 1]])
                ->select('collection_name','original_image','thumbnail','is_default')
                ->first();
            if(empty($collection)){
                return $this->createResult('M08003',(object)array());
            }
        }
        $product->collection_name = $collection->collection_name;
        $this->get_product_preview_images($product);
        $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
        $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
        $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
        //获取明细
        $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
        $cost_detail_list = array();
        $cost_detail_list[] = array(
            'resource_id'=>$product->product_temp_id,
            'title'=>$product->brand_name.$product->product_temp_name,
            'preferential_price'=>GeneralTool::priceFormat($product_temp->preferential_price),
            'original_price'=>GeneralTool::priceFormat($product_temp->original_price),
            'thumbnail'=>$product_temp->thumbnail,
            'quantity'=>1,
            'type'=>1
        );
        $source_pic_detail = $this->product_tool->get_product_used_source_pic_detail($product->product_id,$product->product_temp_id);
        $font_detail = $this->product_tool->get_product_used_font_detail($product->product_id);
        $custom_source_pic_detail = $this->product_tool->get_product_used_customizations_source_pic_detail($product->product_id);
        $cost_detail_list = array_merge($cost_detail_list,$source_pic_detail,$font_detail,$custom_source_pic_detail);
        $product->lists =  $cost_detail_list;
        $product->original_price = GeneralTool::priceFormat(bcsub($product->original_price,$product->overflow_price,2));
        $product->preferential_price = GeneralTool::priceFormat(bcsub($product->preferential_price,$product->overflow_price,2));
        return $this->createResult('M00000',$product);
    }

    /**
     * 上下架
     * @param $user_id
     * @param $product_id
     * @return array
     */
    public function shelvesProduct($input)
    {
        $this->setParameter(array('table' => 'products', 'where' => array(array('product_id', '=', $input['product_id']), array('user_id', '=', $input['user_id']), array('state', '=', 1)), 'select' => array('colour_id', 'product_temp_id', 'product_id', 'is_shelves', 'overflow_price','price as original_price','preferential_price')));
        $product = $this->getById();
        if (empty($product)) {
            return $this->createResult('M08001', (object)array());
        }
        $update_data = array();
        if ($input['type'] == 2 || ($input['type'] == 1 || $product->is_shelves == 0)) {
            if(isset($input['user_collection_id']) && !empty($input['user_collection_id'])){
                $collection = $this->user_collections_service->get_collection_by_user_id_collection_id($input['user_id'],$input['user_collection_id']);
            }
            if(!isset($collection) || empty($collection)){
                return $this->createResult('M08003',(object)array());
            }
            $update_data['user_collection_id'] = $input['user_collection_id'];
            //上架（上架要填写参数）
            if ($input['overflow_price'] == null || $input['stock'] == null || $input['off_shelves_time'] == null) {
                return $this->createResult('M00002', (object)array());
            }
            if($input['overflow_price'] > 10000){
                return $this->createResult('M08021', (object)array());
            }
            $update_data['overflow_price'] = $input['overflow_price'];
            $update_data['stock'] = $input['stock'];
            if(!($input['off_shelves_time'] == 0 || ($input['off_shelves_time'] != 0 && $input['off_shelves_time'] > (time()+ 3600)))){
                return $this->createResult('M08008',(object)array());
            }
            $update_data['off_shelves_time'] = $input['off_shelves_time'];
            if ($input['overflow_price'] != $product->overflow_price) {
                //计算新的产品价格 将原产品减去溢价 之后再加上新的溢价
                //$price = $this->getTotalPrice($product);
                $update_data['price'] = bcadd(bcsub($product->original_price,$product->overflow_price,2),$input['overflow_price'],2);
                $update_data['preferential_price'] = bcadd(bcsub($product->preferential_price,$product->overflow_price,2),$input['overflow_price'],2);
            }
            if ($input['stock'] == 0) {
                //不限制数量
                $update_data['is_infinite_stock'] = 1;
            } else {
                $update_data['is_infinite_stock'] = 0;
            }
            if ($input['off_shelves_time'] == 0) {
                $update_data['is_infinite_time'] = 1;
            } else {
                $update_data['is_infinite_time'] = 0;
            }
        }
        if($input['type'] != 2){
            $shelves = $product->is_shelves == 0 ? 1 : 0;
            $update_data['is_shelves'] = $shelves;
        }else{
            $update_data['is_shelves'] = $product->is_shelves;
        }
        $update_data['updated_at'] = time();
        $this->table = 'products';
        $this->where = array(array('product_id', '=', $input['product_id']));
        $result = $this->update($update_data);
        if(empty($result)){
            return $this->createResult('M00003', (object)array());
        }elseif($input['type'] == 2){
            return $this->createResult('M00000',array('is_shelves' => $update_data['is_shelves']),'','编辑成功',0);
        }else{
            return $update_data['is_shelves'] == 1 ? $this->createResult('M00000',array('is_shelves' => $update_data['is_shelves']),'','作品已上架',0) : $this->createResult('M00000',array('is_shelves' => $update_data['is_shelves']),'','作品已下架',0);
        }
    }
    /**
     * 删除产品
     * @param $input
     * @return array
     */
    public function deleteProduct($input)
    {
        $product = $this->exitProducts($input['user_id'], $input['product_id']);
        if (empty($product)) {
            return $this->createResult('M08001', (object)array());
        }
        //更新
        $update_data = array('state' => 2, 'updated_at' => time());
        $this->table = 'products';
        $this->where = array(array('product_id', '=', $input['product_id']));
        $result = $this->update($update_data);
        return empty($result) ? $this->createResult('M00003', (object)array()) : $this->createResult('M00000', (object)array(),'','作品已删除',0);
    }
    /**
     * 获取产品详情
     * @param $input
     * @return array
     */
    public function get_product_detail($input)
    {
        try {
            $this->setParameter([
                'table' => 'products',
                'where' => [['product_id', '=', $input['product_id']], ['state', '=', 1]],
                'select' => [
                    'product_id', 'user_id', 'colour_id', 'product_temp_id', 'overflow_price', 'sell_num',
                    'is_shelves', 'stock', 'is_infinite_stock', 'collect_num','is_infinite_time','off_shelves_time',
                    'price as original_price','preferential_price'
                ]
            ]);
            $product = $this->getById();
            if (empty($product)) {
                return $this->createResult('M08014', (object)array());
            }
            //判断下架状态
            $product->dis_user_info = 1;
            if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                $product->is_shelves = 0;
            }
            if($product->is_shelves == 0){
                $product->dis_user_info = 0;
            }
            $this->get_product_preview_images($product);
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
            $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
            $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
            $colour_name = ColourTool::getColourSimpleInfoByColourId(intval($product->colour_id));
            $size_names = ProductTempTool::getProdTempSizesByProdTempId($product->product_temp_id);
            if (empty($product_temp) || ($product_temp->state != 1) || empty($colour_name) || empty($size_names)) {
                $product->product_temp_sold_out = 1;
            } else {
                $product->product_temp_sold_out = 1;
                foreach ($size_names as $size_name) {
                    $product_temp_stock = ProductTempTool::getStock($product->product_temp_id, $colour_name->colour_name, $size_name);
                    if (isset($product_temp_stock['stock']) && ($product_temp_stock['stock'] > 0)) {
                        $product->product_temp_sold_out = 0;//还未售罄
                        break;
                    }
                }
            }
            $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
            foreach($product->gift as $key=>$gift){
                $gift->quantity = $gift->num;
            }
            //获取用户头像名称
            $user = $this->userTool->userInfoByid($product->user_id);
            $product->nick_name = $user->nick_name;
            $product->avatar = $user->avatar;
            //获取收藏用户
            $product = $this->get_favorites_user_ids_by_product_id($product, $input['product_id'], $input['user_id']);
            $product->product_sold_out = $product->is_infinite_stock == 1 || $product->stock > 0 ? 0 : 1;
            //$price_arr = $this->getTotalPrice($product);
            $product->original_price = GeneralTool::priceFormat($product->original_price);
            $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
            $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
            //$package = ProductTempTool::getProdTempPostageByProdTempId($product->product_temp_id);
            $product->share_url = env('WEI_SHOP_URL') . 'showProduct?product_id=' . $product->product_id;
            //判断是否是android
            $isAndroid = ProductTempTool::isAndroidByPlatform($input['platform']);
            $product->product_temp_detail_url = $isAndroid ? (env("CURRENT_HTTP_DOMAIN").'/api/goods-detail?product_id=' . $product->product_id) : asset('api/goods-detail?product_id=' . $product->product_id);
            //$product->product_temp_detail_url = asset('api/goods-detail?product_id=' . $product->product_id);
            //获取该产品在购物车中的数量
            $product->shop_car_quantity = $this->car_tool->get_shop_car_product_can_buy_num(['product_id'=> $product->product_id],$input['user_id']);
            $good_settlement_quantity = empty($input['user_id']) ? 0 : $this->car_tool->get_shop_car_quantity(array('user_id'=>$input['user_id']),2)['good_settlement_quantity'];
            $product->good_settlement_quantity = $good_settlement_quantity;//购物车商品数量
            if (($input['user_id'] != $product->user_id && $product->is_shelves == 0) || $product->product_sold_out == 1 || $product->product_temp_sold_out == 1) {
                $product->is_sale = 0;//不能出售
            } else {
                $product->is_sale = 1;//出售
            }
            $announcements = Announcements::where(['state'=>1])
                ->where('announcement_begin_time','<',time())
                ->where('announcement_end_time','>=',time())
                ->select('announcement_id','announcement_content','announcement_type',
                    'announcement_begin_time','announcement_end_time')
                ->orderBy('updated_at','desc')
                ->get()
                ->toArray();
            foreach($announcements as $key=>$announcement){
                $announcements[$key]['url'] = $announcement['announcement_type']== 2 ?
                    asset('api/announcements/detail/'.$announcement['announcement_id']) : '';
            }
            $product->announcement_list = $announcements;
            return $this->createResult('M00000', $product);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M08009', (object)array());
        }
    }
    /**
     * 获取立即购买和加入购物车所需参数
     * @param $product_id
     * @return array
     */
    public function get_order_product_parameters($user_id,$product_id)
    {
        try {
            $this->setParameter([
                'table' => 'products',
                'where' => [['product_id', '=', $product_id],['state', '=', 1]],
                'select' => [
                    'product_id', 'user_id', 'colour_id', 'product_temp_id', 'overflow_price',
                    'stock', 'is_infinite_stock', 'prod_md5','is_shelves','is_infinite_time','off_shelves_time',
                    'price as original_price','preferential_price'
                ]
            ]);
            $product = $this->getById();
            if (empty($product)) {
                return $this->createResult('M08014', (object)array());
            }
            //判断下架状态
//            if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
//                $product->is_shelves = 0;
//            }
//            if($user_id != $product->user_id && $product->is_shelves != 1){
//                return $this->createResult('M08011', (object)array());
//            }
            //根据$product_id获取一组ID
            $this->setParameter([
                'table' => 'products',
                'where' => [['user_id', '=', $product->user_id], ['product_id', '<>', $product_id], ['prod_md5', '=', $product->prod_md5], ['state', '=', 1]],
                'select' => [
                    'product_id', 'user_id', 'colour_id', 'product_temp_id', 'overflow_price', 'stock',
                    'is_infinite_stock', 'prod_md5','is_shelves','is_infinite_time','off_shelves_time',
                    'price as original_price','preferential_price'
                ]
            ]);
            if($user_id != $product->user_id){
                $this->where[] = ['is_shelves', '=', 1];
            }
            $products = $this->getAll()->toArray();
            array_unshift($products, $product);
            foreach ($products as $product) {
                $product->dis_user_info = 1;
                if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                    $product->is_shelves = 0;
                }
                if($product->is_shelves == 0){
                    $product->dis_user_info = 0;
                }
                $this->get_product_preview_images($product);
                $product = $this->get_product_temp_paramter($product);
                $product->product_sold_out = $product->is_infinite_stock == 1 || $product->stock > 0 ? 0 : 1;
                //$price_arr = $this->getTotalPrice($product);
                $product->original_price = GeneralTool::priceFormat($product->original_price);
                $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
                $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
                //获取该产品在购物车中的数量
                $product->shop_car_quantity = $this->car_tool->get_shop_car_product_can_buy_num(['product_id'=> $product->product_id],$user_id);
                if (($user_id != $product->user_id && $product->is_shelves == 0) || $product->product_sold_out == 1 || $product->product_temp_sold_out == 1) {
                    $product->is_sale = 0;//不能出售
                } else {
                    $product->is_sale = 1;//出售
                }
            }
            return $this->createResult('M00000', $products);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M08009', (object)array());
        }
    }
    /**
     * 获取产品详情
     * @param $input
     * @return array
     */
    public function get_products_detail($input)
    {
        try {
            $this->setParameter([
                'table' => 'products',
                'where' => [['product_id', '=', $input['product_id']], ['state', '=', 1]],
                'select' => [
                    'product_id', 'user_id', 'colour_id', 'product_temp_id', 'overflow_price', 'sell_num', 'is_shelves',
                    'stock', 'is_infinite_stock', 'collect_num', 'prod_md5','is_infinite_time','off_shelves_time',
                    'price as original_price','preferential_price'
                ]
            ]);
            $product = $this->getById();
            if (empty($product)) {
                return $this->createResult('M08014', (object)array());
            }
            //根据$product_id获取一组ID
            $this->setParameter([
                'table' => 'products',
                'where' => [
                    ['user_id', '=', $product->user_id],
                    ['product_id', '<>', $input['product_id']],
                    ['prod_md5', '=', $product->prod_md5],
                    ['state', '=', 1]
                ],
                'select' => [
                    'product_id', 'user_id', 'colour_id', 'product_temp_id', 'overflow_price', 'sell_num', 'is_shelves',
                    'stock', 'is_infinite_stock', 'collect_num', 'prod_md5','is_infinite_time','off_shelves_time',
                    'price as original_price','preferential_price'
                ]
            ]);
            if($input['user_id'] != $product->user_id){
                $this->where[] = ['is_shelves', '=', 1];
            }
            $products = $this->getAll()->toArray();
            array_unshift($products, $product);
            $announcements = Announcements::where(['state'=>1])
                ->where('announcement_begin_time','<',time())
                ->where('announcement_end_time','>=',time())
                ->select('announcement_id','announcement_content','announcement_type',
                    'announcement_begin_time','announcement_end_time')
                ->orderBy('updated_at','desc')
                ->get()
                ->toArray();
            foreach($announcements as $key=>$announcement){
                $announcements[$key]['url'] = $announcement['announcement_type']== 2 ?
                    asset('api/announcements/detail/'.$announcement['announcement_id']) : '';
            }
            foreach ($products as $product) {
                //判断下架状态
                $product->dis_user_info = 1;
                if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                    $product->is_shelves = 0;
                }
                if($product->is_shelves == 0){
                    $product->dis_user_info = 0;
                }
                $this->get_product_preview_images($product);
                $product = $this->get_product_temp_paramter($product);
                $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
                foreach($product->gift as $key=>$gift){
                    $gift->quantity = $gift->num;
                }
                //获取用户头像名称
                $user = $this->userTool->userInfoByid($product->user_id);
                $product->nick_name = $user->nick_name;
                $product->avatar = $user->avatar;
                //获取收藏用户
                $product = $this->get_favorites_user_ids_by_product_id($product, $input['product_id'], $input['user_id']);
                $product->product_sold_out = $product->is_infinite_stock == 1 || $product->stock > 0 ? 0 : 1;
                //$price_arr = $this->getTotalPrice($product);
                $product->original_price = GeneralTool::priceFormat($product->original_price);
                $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
                $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
                //$package = ProductTempTool::getProdTempPostageByProdTempId($product->product_temp_id);
                $product->share_url = env('WEI_SHOP_URL') . 'showProduct?product_id=' . $product->product_id;
                //判断是否是android
                $isAndroid = ProductTempTool::isAndroidByPlatform($input['platform']);
                $product->product_temp_detail_url = $isAndroid ? (env("CURRENT_HTTP_DOMAIN").'/api/goods-detail?product_id=' . $product->product_id) : asset('api/goods-detail?product_id=' . $product->product_id);
                //$product->product_temp_detail_url = asset('api/goods-detail?product_id=' . $product->product_id);
                //获取该产品在购物车中的数量
                $product->shop_car_quantity = $this->car_tool->get_shop_car_product_can_buy_num(['product_id'=> $product->product_id],$input['user_id']);
                $good_settlement_quantity = empty($input['user_id']) ? 0 : $this->car_tool->get_shop_car_quantity(array('user_id'=>$input['user_id']),2)['good_settlement_quantity'];
                $product->good_settlement_quantity = $good_settlement_quantity;
                if (($input['user_id'] != $product->user_id && $product->is_shelves == 0) || $product->product_sold_out == 1 || $product->product_temp_sold_out == 1) {
                    $product->is_sale = 0;//不能出售
                } else {
                    $product->is_sale = 1;//出售
                }
                $product->announcement_list = $announcements;
            }
            return $this->createResult('M00000', $products);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M08009', (object)array());
        }
    }
    /**
     * @param $product
     * @param $product_id //查找产品ID
     * @param $user_id
     */
    public function get_favorites_user_ids_by_product_id($product, $product_id, $user_id)
    {
        $user_ids = $this->favorites_service->get_favorites_user_ids_by_product_id($product_id, 3, 10);
        $product->is_favorite = in_array($user_id, $user_ids) == true ? 1 : 0;
        $user_avatars = $this->userTool->headerImgs($user_ids);
        $product->favorite_user_avatars = $user_avatars;
        return $product;
    }
    /**
     * 设置产品模板参数
     * @param $product
     * @return mixed
     */
    public function get_product_temp_paramter($product)
    {
        $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
        $product->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
        $product->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;
        $colour_name = ColourTool::getColourSimpleInfoByColourId(intval($product->colour_id));
        $product->colour = $colour_name === null ? (object)array() : $colour_name;
        $size_names = ProductTempTool::getProdTempSizesByProdTempId($product->product_temp_id);
        $size_arr = array();
        if (empty($product_temp) || ($product_temp->state != 1) || empty($colour_name) || empty($size_names)) {
            $product->product_temp_sold_out = 1;
            $r = 0;
            foreach ($size_names as $size_name) {
                $size_arr[$r]['size_name'] = $size_name;
                $size_arr[$r]['num'] = 0;
                $r = $r + 1;
            }
        } else {
            $r = 0;
            $product->product_temp_sold_out = 1;
            foreach ($size_names as $size_name) {
                $product_temp_stock = ProductTempTool::getStock($product->product_temp_id, $colour_name->colour_name, $size_name);
                if (isset($product_temp_stock['stock']) && ($product_temp_stock['stock'] > 0)) {
                    //$size_arr[$size_name] = $product_temp_stock['stock'];
                    $size_arr[$r]['size_name'] = $size_name;
                    $size_arr[$r]['num'] = $product_temp_stock['stock'];
                    $r = $r + 1;
                    $product->product_temp_sold_out = 0;
                } else {
                    $size_arr[$r]['size_name'] = $size_name;
                    $size_arr[$r]['num'] = 0;
                    $r = $r + 1;
                }
            }
        }
        $product->sizes = $size_arr;
        return $product;
    }
    /**
     * 检查创作参数
     * @param $input
     * @return array
     */
    public function checkParamters($input,$type=0)
    {
        $user_type = $this->userTool->userType($input['user_id']);
        if ($user_type === null) {
            return $this->createResult('M08004', (object)array());
        }
        if(($type == 0 && $user_type != 0) || ($type == 1 && $user_type == 0)){
            return $this->createResult('M08023', (object)array());
        }
        $input['user_type'] = $user_type;
        $input['product_templates'] = json_decode($input['product_templates']);
        if (is_null($input['product_templates']) || empty($input['product_templates'])) {
            return $this->createResult('M08015', (object)array(), 'globalcodes', 'product_templates');
        }
        if($user_type == 0 && count($input['product_templates']) > 1){
            return $this->createResult('M08022',(object)array());
        }
        if(is_null($input['platform']) || !isset(config('fashion.channel')[strtolower($input['platform'])])){
            return $this->createResult('M08015',(object)array(),'globalcodes','platform');
        }
        $input['channel'] = config('fashion.channel')[strtolower($input['platform'])];
        if(is_null($input['screen_size'])){
            return $this->createResult('M08015',(object)array(),'globalcodes','screen_size');
        }
        $sizes = explode('x',$input['screen_size']);
        if(count($sizes) != 2 || (intval($sizes[0]) == 0 || intval($sizes[1]) == 0)){
            return $this->createResult('M08015',(object)array(),'globalcodes','screen_size');
        }
        $input['sketchpad_width'] = $sizes[1];
        $input['sketchpad_height'] = $sizes[0];
        return $this->createResult('M00000', $input);
    }
    /**
     * 普通用户获取产品明细
     * @param $input
     * @return array
     */
    public function get_product_detail_list($input){
        try {
            $this->setParameter([
                'table' => 'products',
                'where' => [['product_id', '=', $input['product_id']], ['state', '=', 1]],
                'select' => [
                    'product_id', 'user_id', 'colour_id', 'product_temp_id', 'overflow_price', 'sell_num', 'is_shelves',
                    'stock', 'is_infinite_stock', 'collect_num','is_infinite_time','off_shelves_time','price as original_price','preferential_price'
                ]
            ]);
            $product = $this->getById();
            if (empty($product)) {
                return $this->createResult('M08014', (object)array());
            }
            //判断下架状态
            $product->dis_user_info = 1;
            if($product->is_shelves == 1 && ($product->is_infinite_time == 0 && $product->off_shelves_time < time())){
                $product->is_shelves = 0;
            }
            if($product->is_shelves == 0){
                $product->dis_user_info = 0;
            }
            $this->get_product_preview_images($product);
            $this->get_product_temp_paramter($product);
            $product->gift = GiftApiService::getProductGift(array('product_id' => $product->product_id));
            foreach($product->gift as $key=>$gift){
                $gift->quantity = $gift->num;
            }
            $product->product_sold_out = $product->is_infinite_stock == 1 || $product->stock > 0 ? 0 : 1;
            //$price_arr = $this->getTotalPrice($product);
            $product->original_price = GeneralTool::priceFormat($product->original_price);
            $product->preferential_price = GeneralTool::priceFormat($product->preferential_price);
            $product->has_preferential = $product->original_price == $product->preferential_price ? 0 : 1;
            //获取明细
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product->product_temp_id, $product->colour_id,0);
            $cost_detail_list = array();
            $cost_detail_list[] = array(
                'resource_id'=>$product->product_temp_id,
                'title'=>$product->brand_name.$product->product_temp_name,
                'preferential_price'=>GeneralTool::priceFormat($product_temp->preferential_price),
                'original_price'=>GeneralTool::priceFormat($product_temp->original_price),
                'thumbnail'=>$product_temp->thumbnail,
                'quantity'=>1,
                'type'=>1
            );
            $source_pic_detail = $this->product_tool->get_product_used_source_pic_detail($product->product_id,$product->product_temp_id);
            $font_detail = $this->product_tool->get_product_used_font_detail($product->product_id);
            $custom_source_pic_detail = $this->product_tool->get_product_used_customizations_source_pic_detail($product->product_id);
            $cost_detail_list = array_merge($cost_detail_list,$source_pic_detail,$font_detail,$custom_source_pic_detail);
            $product->lists =  $cost_detail_list;
            //获取该产品在购物车中的数量
            $product->shop_car_quantity = $this->car_tool->get_shop_car_product_can_buy_num(['product_id'=> $product->product_id],$input['user_id']);
            $good_settlement_quantity = empty($input['user_id']) ? 0 : $this->car_tool->get_shop_car_quantity(array('user_id'=>$input['user_id']),2)['good_settlement_quantity'];
            $product->good_settlement_quantity = $good_settlement_quantity;//购物车商品数量
            if (($input['user_id'] != $product->user_id && $product->is_shelves == 0) || $product->product_sold_out == 1 || $product->product_temp_sold_out == 1) {
                $product->is_sale = 0;//不能出售
            } else {
                $product->is_sale = 1;//出售
            }
            $announcements = Announcements::where(['state'=>1])
                ->where('announcement_begin_time','<',time())
                ->where('announcement_end_time','>=',time())
                ->select('announcement_id','announcement_content','announcement_type',
                    'announcement_begin_time','announcement_end_time')
                ->orderBy('updated_at','desc')
                ->get()
                ->toArray();
            foreach($announcements as $key=>$announcement){
                $announcements[$key]['url'] = $announcement['announcement_type']== 2 ?
                    asset('api/announcements/detail/'.$announcement['announcement_id']) : '';
            }
            $product->announcement_list = $announcements;
            return $this->createResult('M00000', $product);
        } catch (\Exception $e) {
            Log::info($e);
            return $this->createResult('M08009', (object)array());
        }
    }
    /**
     * 保存打印数据(设计师/普通用户)
     * @param $input
     * @return array
     */
    public function create_product_preview($input)
    {
        //Log::info($input);
        $result = $this->products_create_service->create_product_preview($input);
        if ($result['state'] != 'M00000') {
            return $result;
        }
        //保存数据
        $input = $result['result'];
        $output = array();
        foreach ($input['product_templates'] as $product_temp_data) {
            $product_detail = array();
            //计算价格 前后
            $price = 0;//真实价格
            $preferential_price = 0;//优惠价格
            $has_calculated_source_pic = array();//已经计算过价钱的素材
            $has_calculated_font = array();//已经计算过的字体
            $cost_detail_source_list = array();//素材和字体明细列表
            //模板价格
            $temp_prices = PreferentialService::getResourcePrice($product_temp_data->product_temp_id, 2, $product_temp_data->colour_id);
            $price = bcadd($price,$temp_prices['original_price'],2);
            $preferential_price = bcadd($preferential_price,$temp_prices['preferential_price'],2);
            $product_print_detail = array();
            $original_image = array();
            $thumbnail = array();
            foreach ($product_temp_data->creative_parameters as $creative_parameter) {
                //保存打印参数开始 (一个区域一条 一个作品多个区域)
                if(!empty($creative_parameter->image_parameters)){
                    $product_print_id = DB::table('product_prints')->insertGetId([
                        //'product_id' => $product_id,
                        'user_id' => $input['user_id'],
                        'temp_id' => $product_temp_data->product_temp_id,
                        'colour_id' => $product_temp_data->colour_id,
                        'style_box_w' => $creative_parameter->style_box_w,
                        'style_box_h' => $creative_parameter->style_box_h,
                        'sketchpad_width' => $input['sketchpad_width'],
                        'sketchpad_height' => $input['sketchpad_height'],
                        'position_type' => $creative_parameter->position_type,
                        'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                        'craftsmanship_type' => $creative_parameter->craftsmanship_type,
                        'app_version' => isset($input['app_version']) ? $input['app_version'] : '',
                        'state' => 1,
                        'created_at' => time(),
                        'updated_at' => time()
                    ]);
                    $product_print_detail['product_print_id'] = $product_print_id;
                    foreach ($creative_parameter->image_parameters as $image_parameter) {
                        if ($image_parameter->type == 1) {
                            //图片
                            $product_print_materials_id = DB::table('product_print_materials')->insertGetId([
                                'product_print_id' => $product_print_id,
                                'creative_id' => $image_parameter->creative_id,
                                'craftsmanship_type' => $creative_parameter->craftsmanship_type,
                                'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                                'image_finnal_size_width' => $image_parameter->image_finnal_size_width,
                                'image_finnal_size_height' => $image_parameter->image_finnal_size_height,
                                'mask_finnal_size_height' => isset($image_parameter->mask_finnal_size_height) ? $image_parameter->mask_finnal_size_height : 0,
                                'mask_finnal_size_width' => isset($image_parameter->mask_finnal_size_width) ? $image_parameter->mask_finnal_size_width : 0,
                                'mask_id' => isset($image_parameter->mask_id) ? $image_parameter->mask_id : 0,
                                'mask_center_point_offset_x' => isset($image_parameter->mask_center_point_offset_x) ? $image_parameter->mask_center_point_offset_x : 0,
                                'mask_center_point_offset_y' => isset($image_parameter->mask_center_point_offset_y) ? $image_parameter->mask_center_point_offset_y : 0,
                                'center_point_offset_x' => $image_parameter->image_center_point_offset_x,
                                'center_point_offset_y' => $image_parameter->image_center_point_offset_y,
                                'angle' => $image_parameter->image_angle,
                                'type' => $image_parameter->type,
                                'image_type' => $image_parameter->image_type,
                                'font_svg' => '',
                                'edit_view_level' => $image_parameter->edit_view_level,
                                'is_horizontal_filp' => $image_parameter->is_horizontal_filp,
                                'is_vertical_filp' => $image_parameter->is_vertical_filp,
                                'state' => 1,
                                'created_at' => time(),
                                'updated_at' => time()
                            ]);
                            if($image_parameter->image_type == 2 && !in_array($image_parameter->creative_id,$has_calculated_source_pic)){
                                //计算价格
                                $prices = PreferentialService::getResourcePrice($image_parameter->creative_id, 1);
                                $price = bcadd($price,$prices['original_price'],2);
                                $preferential_price = bcadd($preferential_price,$prices['preferential_price'],2);
                                $has_calculated_source_pic[] = $image_parameter->creative_id;
                                $cost_detail_source_list[] = array('resource_id'=>$image_parameter->creative_id,'title'=>$image_parameter->title,'preferential_price'=>GeneralTool::priceFormat($prices['preferential_price']),'original_price'=>GeneralTool::priceFormat($prices['original_price']),'thumbnail'=>env('IMG_URL_STD_PREFIX').$image_parameter->thumbnail,'quantity'=>1,'type'=>3);
                            }
                            if($image_parameter->image_type == 1){
                                $cost_detail_source_list[] = array('resource_id'=>$image_parameter->creative_id,'title'=>$image_parameter->title,'preferential_price'=>0,'original_price'=>0,'thumbnail'=>env('IMG_URL_STD_PREFIX').$image_parameter->thumbnail,'quantity'=>1,'type'=>2);
                            }
                        } else {
                            $product_print_materials_id = DB::table('product_print_materials')->insertGetId([
                                'product_print_id' => $product_print_id,
                                'craftsmanship_type' => $creative_parameter->craftsmanship_type,
                                'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                                'center_point_offset_x' => $image_parameter->font_center_point_offset_x,
                                'center_point_offset_y' => $image_parameter->font_center_point_offset_y,
                                'angle' => $image_parameter->font_angle,
                                'type' => 2,
                                'edit_view_level' => $image_parameter->edit_view_level,
                                'text' => $image_parameter->text,
                                'font_id' => $image_parameter->font_id,
                                'font_size' => $image_parameter->font_size,
                                'font_color' => $image_parameter->font_color,
                                'font_alpha' => $image_parameter->font_alpha,
                                'font_svg' => isset($image_parameter->font_svg) ? json_encode($image_parameter->font_svg) : '',
                                'state' => 1,
                                'created_at' => time(),
                                'updated_at' => time()
                            ]);
                            if(!in_array($image_parameter->font_id,$has_calculated_font)){
                                $prices = PreferentialService::getResourcePrice($image_parameter->font_id, 3);
                                $price = bcadd($price,$prices['original_price'],2);
                                $preferential_price = bcadd($preferential_price,$prices['preferential_price'],2);
                                $has_calculated_font[] = $image_parameter->font_id;
                                $cost_detail_source_list[] = array('resource_id'=>$image_parameter->font_id,'title'=>$image_parameter->font_name,'preferential_price'=>GeneralTool::priceFormat($prices['preferential_price']),'original_price'=>GeneralTool::priceFormat($prices['original_price']),'thumbnail'=>env('IMG_URL_STD_PREFIX').$image_parameter->font_image,'quantity'=>1,'type'=>4);
                            }
                        }
                    }
                    $original_image[] = env('IMG_URL_STD_PREFIX').$creative_parameter->image_path;
                    $thumbnail[] = env('IMG_URL_STD_PREFIX').$creative_parameter->image_path;
                    $product_print_detail['original_image'] = env('IMG_URL_STD_PREFIX').$creative_parameter->image_path;
                    $product_print_detail['thumbnail'] = env('IMG_URL_STD_PREFIX').$creative_parameter->image_path;
                    $product_detail['product_print_detail'][] =  $product_print_detail;
                }
            }
            $product_detail['original_image'] = $original_image;
            $product_detail['thumbnail'] = $thumbnail;
            $product_detail['original_price'] = GeneralTool::priceFormat($price);
            $product_detail['preferential_price'] = GeneralTool::priceFormat($preferential_price);
            $product_detail['product_temp_id'] = $product_temp_data->product_temp_id;
            $colour_name = ColourTool::getColourSimpleInfoByColourId(intval($product_temp_data->colour_id));
            $product_detail['colour'] = $colour_name === null ? (object)array() : $colour_name;
            //保存产品数据
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product_temp_data->product_temp_id, $product_temp_data->colour_id,0);
            //产品明细列表
            $cost_detail_list = array();
            $cost_detail_list[] = array('resource_id'=>$product_temp_data->product_temp_id,'title'=>$product_temp->brand_name.$product_temp->product_temp_name,'preferential_price'=>GeneralTool::priceFormat($product_temp->preferential_price),'original_price'=>GeneralTool::priceFormat($product_temp->original_price),'thumbnail'=>$product_temp->thumbnail,'quantity'=>1,'type'=>1);
            $cost_detail_list = array_merge($cost_detail_list,$cost_detail_source_list);
            //素材明细
            $product_detail['lists'] = $cost_detail_list;
            $output[] = $product_detail;
        }
        return $this->createResult('M00000',$output);
    }
    /**
     * 发布产品(设计师)
     * @param $input
     * @return array
     */
    public function save_product($input){
        //生成为md5值 标志这是一组一起生成 $product_temp_id
        $prod_md5 = md5(date('ymdhis') . rand(1, 10000) . $input['user_id']);
        $user_type = $this->userTool->userType($input['user_id']);
        if($user_type === null || $user_type == 0){
            return $this->createResult('M08019', (object)array());
        }
        if(!isset($input['platform']) || is_null($input['platform']) || !isset(config('fashion.channel')[strtolower($input['platform'])])){
            return $this->createResult('M08015',(object)array(),'globalcodes','platform');
        }
        $channel = config('fashion.channel')[strtolower($input['platform'])];
        $product_ids = [];
        $print_param = array();//打印参数
        $result = array();
        $return_result = [];
        try{
            DB::beginTransaction();
            foreach($input['products'] as $product_param){
                $return_result_detail = [];
                $print_param_details = array();
                $product_id = GeneralTool::only_no();
                $insert_data = array();
                $insert_data['channel'] = $channel;
                $insert_data['product_id'] = $product_id;
                $insert_data['prod_md5'] = $prod_md5;
                if(!isset($product_param->product_print_detail) && count($product_param->product_print_detail) <= 0){
                    $result = $this->createResult('M08028',array());
                    return $result;
                }
                if(isset($product_param->colour_id) && is_numeric($product_param->colour_id)){
                    $insert_data['colour_id'] = $product_param->colour_id;
                }else{
                    $result = $this->createResult('M08028',array());
                    return $result;
                }
                if(isset($product_param->product_temp_id) && is_numeric($product_param->product_temp_id)){
                    $insert_data['product_temp_id'] = $product_param->product_temp_id;
                    $is_exit_temp = $this->product_temp_tool->productTempColourExistByProductTempIdAndColourId($product_param->product_temp_id,$product_param->colour_id,1);
                    if($is_exit_temp == false){
                        $result = $this->createResult('M08028',array());
                        return $result;
                    }
                    $insert_data['product_temp_id'] = $product_param->product_temp_id;
                }else{
                    $result = $this->createResult('M08028',array());
                    return $result;
                }
                
                if(isset($product_param->is_shelves) && is_integer($product_param->is_shelves) && $product_param->is_shelves == 1){
                    $insert_data['is_shelves'] = $product_param->is_shelves;
                    if(isset($product_param->user_collection_id) && is_numeric($product_param->user_collection_id)){
                        $collection = $this->user_collections_service->get_collection_by_user_id_collection_id($input['user_id'],$product_param->user_collection_id);
                        if(empty($collection)){
                            $result = $this->createResult('M08003',(object)array());
                            return $result;
                        }
                        $insert_data['user_collection_id'] = $product_param->user_collection_id;
                    }else{
                        $collection_id = DB::table('user_collections')->where([['user_id', '=', $input['user_id']], ['is_default', '=', 1]])->value('collection_id');
                        if(empty($collection_id)){
                            $result = $this->createResult('M08003',(object)array());
                            return $result;
                        }
                        $insert_data['user_collection_id'] = $collection_id;
                    }
                    if(isset($product_param->overflow_price) && is_numeric($product_param->overflow_price)){
                        if($product_param->overflow_price > 10000){
                            $result = $this->createResult('M08021', (object)array());
                            return $result;
                        }
                        $insert_data['overflow_price'] = $product_param->overflow_price;
                    }
                    if(isset($product_param->off_shelves_time)){
                        $insert_data['off_shelves_time'] = intval($product_param->off_shelves_time);
                    }
                    if(isset($product_param->is_infinite_time) && is_integer($product_param->is_infinite_time)){
                        $insert_data['is_infinite_time'] = $product_param->is_infinite_time;
                    }
                    if($insert_data['is_infinite_time'] != 1 && $insert_data['off_shelves_time'] < (time()+ 3600)){
                        //有限时间 且时间不大于当前时间一个小时
                        $result = $this->createResult('M08008',(object)array());
                        return $result;
                    }
                    if(isset($product_param->stock) && is_integer($product_param->stock)){
                        $insert_data['stock'] = $product_param->stock;
                    }
                    if(isset($product_param->is_infinite_stock) && is_integer($product_param->is_infinite_stock)){
                        $insert_data['is_infinite_stock'] = $product_param->is_infinite_stock;
                    }
                }else{
                    $insert_data['is_shelves'] = 0;
                    $collection_id = DB::table('user_collections')->where([['user_id', '=', $input['user_id']], ['is_default', '=', 1]])->value('collection_id');
                    if(empty($collection_id)){
                        $result = $this->createResult('M08003',(object)array());
                        return $result;
                    }
                    $insert_data['user_collection_id'] = $collection_id;
                }
                $insert_data['user_id'] = $input['user_id'];
                $insert_data['created_at'] = $insert_data['updated_at'] = time();
                $product_insert_flag = DB::table('products')->insert($insert_data);
                if(empty($product_insert_flag)){
                    $result = $this->createResult('M08028',(object)array());
                    return $result;
                }
                //保存product_id
                $product_print_detail_re = [];
                $return_result_detail['product_print_detail'] = [];
                $product_print_materials = array();
                foreach($product_param->product_print_detail as $print){
                    $product_print_materials_detail = array();
                    $product_print = DB::table('product_prints')
                        ->where('id',$print->product_print_id)
                        ->select('id','temp_id','colour_id','position_type','craftsmanship_name')
                        ->first();
                    if(empty($product_print) || $product_print->temp_id != $product_param->product_temp_id || $product_print->colour_id != $product_param->colour_id){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    $flag_product_prints = DB::table('product_prints')->where('id',$print->product_print_id)
                        ->update(['product_id'=>$product_id,'updated_at'=>time()]);
                    $flag_product_print_materials = DB::table('product_print_materials')->where('product_print_id',$product_print->id)->update(['product_id'=>$product_id,'updated_at'=>time()]);
                    if(empty($flag_product_prints) || empty($flag_product_print_materials)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //保存图片
                    //判断是否存在图片
                    $print->original_image = ImgTool::getImgPathByImgUrl($print->original_image);
                    $print->thumbnail = ImgTool::getImgPathByImgUrl($print->thumbnail);
                    if(empty($print->original_image) || !file_exists(public_path().self::PREFIX_PATH.$print->original_image)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    if(empty($print->thumbnail) || !file_exists(public_path().self::PREFIX_PATH.$print->thumbnail)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //Todo(缩略图与轮播图是一样)
                    //将图片转移
                    $old_file = public_path().self::PREFIX_PATH.$print->original_image;
                    //图片格式
                    $extension = '.'.$this->imagick_tool->getImageExt($old_file);
                    $prefix_name = md5(date('ymdhis').rand(1, 1000));
                    $child_folder = date('Ym',time());
                    $folder = public_path() .self::PREFIX_PATH.self::IMAGE_PATH.$child_folder;
                    $this->imagick_tool->mkFolder($folder);
                    $new_file = $folder.'/'.$prefix_name.$extension;
                    $output = shell_exec("mv ".$old_file." ".$new_file." &&  echo 'success'");
                    if(empty($output)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //判断图片唯一性
                    $md5_image = md5_file($new_file);
                    rename($new_file,$folder.'/'.$md5_image.$extension);
                    $real_path = ImgTool::saveImgToDbByImgPath(self::IMAGE_PATH.$child_folder.'/'.$md5_image.$extension);
                    //保存缩率图
                    $insert_preview_data = array(
                        'product_id' => $product_id,
                        'product_preview_original_image' => $real_path,
                        'product_preview_thumbnail_image' => $real_path,
                        'position_type' => $product_print->position_type,
                        'craftsmanship_name' => $product_print->craftsmanship_name,
                        'created_at' => time(),
                        'updated_at' => time()
                    );
                    $product_preview_image_id = DB::table('product_preview_images')->insertGetId($insert_preview_data);
                    if(empty($product_preview_image_id)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    $product_print_materials_ids = DB::table('product_print_materials')->where('product_print_id',$print->product_print_id)->pluck('id')->toArray();
                    $product_print_materials_detail['product_print_id'] = $product_print->id;
                    $product_print_materials_detail['product_print_materials_ids'] = $product_print_materials_ids;
                    $product_print_materials_detail['position_type'] = $product_print->position_type;
                    $product_print_materials_detail['product_preview_image_id'] = $product_preview_image_id;
                    $product_print_materials[] = $product_print_materials_detail;
                    $return_result_detail['original_image'][] = env('IMG_URL_STD_PREFIX').$real_path;
                    $return_result_detail['thumbnail'][] = env('IMG_URL_STD_PREFIX').$real_path;
                    $product_print_detail_re['product_print_id'] = $print->product_print_id;
                    $product_print_detail_re['original_image'] = $product_print_detail_re['thumbnail'] = env('IMG_URL_STD_PREFIX').$real_path;
                    $return_result_detail['product_print_detail'][] = $product_print_detail_re;
                }
                //计算产品价格
                $product = DB::table('products')->where('product_id',$product_id)->select('product_id','product_temp_id','colour_id','overflow_price')->first();
                $prices = $this->getTotalPrice($product);
                //更新价格
                if($prices['total_price'] != 0 || $prices['total_preferential_price'] != 0){
                    $product_price_flag = DB::table('products')->where('product_id',$product_id)->update(['price'=>$prices['total_price'],'preferential_price'=>$prices['total_preferential_price'],'updated_at'=>time()]);
                    if(empty($product_price_flag)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                }
                $print_param_details['product_id'] = $product_id;
                $print_param_details['product_print_materials'] = $product_print_materials;
                $print_param[] = $print_param_details;
                $product_ids[] = $product_id;


                $colour_name = ColourTool::getColourSimpleInfoByColourId(intval($product_param->colour_id));
                $colour = $colour_name === null ? (object)array() : $colour_name;
                $return_result_detail['colour'] = $colour;
                $return_result_detail['product_temp_id'] = $product_param->product_temp_id;
                $return_result_detail['product_draft_id'] = 0;
                $return_result_detail['original_price'] = GeneralTool::priceFormat($prices['total_price']);
                $return_result_detail['preferential_price'] = GeneralTool::priceFormat($prices['total_preferential_price']);
                $cost_detail_list = [];
                $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product_param->product_temp_id, $product_param->colour_id,0);
                $cost_detail_list[] = array(
                    'resource_id'=>$product_param->product_temp_id,
                    'title'=>$product_temp->brand_name.$product_temp->product_temp_name,
                    'preferential_price'=>GeneralTool::priceFormat($product_temp->preferential_price),
                    'original_price'=>GeneralTool::priceFormat($product_temp->original_price),
                    'thumbnail'=>$product_temp->thumbnail,
                    'quantity'=>1,
                    'type'=>1
                );
                $material_detail = $this->get_material_detail($product_id, $product_param->product_temp_id, 1);
                $customize_material_detail = $this->get_customiz_material_detail($product_id, 1);
                $font_detail = $this->get_font_detail($product_id, 1);
                $cost_detail_list = array_merge($cost_detail_list,$material_detail,$customize_material_detail,$font_detail);
                $return_result_detail['lists'] = $cost_detail_list;
                $return_result[] = $return_result_detail;

                $this->userTool->addCreateNumToAuthentication($input['user_id']);
                //增加模板使用量
                ProductTempTool::increasedProdTempUsedNum($product_param->product_temp_id,1);
            }
            //删除草稿
            if(isset($input['product_draft_md5']) && !empty($input['product_draft_md5'])){
                $update_res = DB::table('product_drafts')
                  ->where(['md5'=>$input['product_draft_md5'],'user_id'=>$input['user_id'],'state'=>1]) 
                  ->update(['state'=>2,'updated_at'=>time()]);
                if(empty($update_res)){
                    $result = $this->createResult('M08028',(object)array());
                    return $result;
                }  
            }

            Log::info('-------------------设计师图片打印开始begin---------------------------');
            dispatch(new Php2PyImg($print_param));
            Log::info('-------------------设计师图片打印开始end---------------------------');
            $result = $this->createResult('M00000',array('product_id'=>$product_ids[0],'product_draft_md5'=>'','data'=>$return_result));
            return $result;
        }catch (\Exception $e){
            Log::info($e);
            DB::rollback();
            $result = $this->createResult('M08028',(object)array());
            return $result;
        }finally{
            if(empty($result) || $result['state'] != 'M00000'){
                DB::rollback();
            }
            DB::commit();
        }
    }
    /**
     * 发布产品(普通用户)
     * @param $input
     * @return array
     */
    public function common_save_product($input){
        //生成为md5值 标志这是一组一起生成 $product_temp_id
        $prod_md5 = md5(date('ymdhis') . rand(1, 10000) . $input['user_id']);
        $user_type = $this->userTool->userType($input['user_id']);
        if($user_type === null || $user_type != 0){
            return $this->createResult('M08023', (object)array());
        }
        if(!isset($input['platform']) || is_null($input['platform']) || !isset(config('fashion.channel')[strtolower($input['platform'])])){
            return $this->createResult('M08028',(object)array(),'globalcodes','platform');
        }
        $channel = config('fashion.channel')[strtolower($input['platform'])];
        $print_param = array();//打印参数
        $product_ids = [];
        $result = array();
        $return_result = [];
        try{
            DB::beginTransaction();
            foreach($input['products'] as $product_param){
                $return_result_detail = [];
                $product_id = GeneralTool::only_no();
                $insert_data = array();
                $insert_data['channel'] = $channel;
                $insert_data['product_id'] = $product_id;
                $insert_data['prod_md5'] = $prod_md5;
                if(!isset($product_param->product_print_detail) && count($product_param->product_print_detail) <= 0){
                    $result = $this->createResult('M08028',array());
                    return $result;
                }
                if(isset($product_param->colour_id) && is_numeric($product_param->colour_id)){
                    $insert_data['colour_id'] = $product_param->colour_id;
                }else{
                    $result = $this->createResult('M08028',array());
                    return $result;
                }
                if(isset($product_param->product_temp_id) && is_numeric($product_param->product_temp_id)){
                    $insert_data['product_temp_id'] = $product_param->product_temp_id;
                    $is_exit_temp = $this->product_temp_tool->productTempColourExistByProductTempIdAndColourId($product_param->product_temp_id,$product_param->colour_id,1);
                    if($is_exit_temp == false){
                        $result = $this->createResult('M08010',array());
                        return $result;
                    }
                    $insert_data['product_temp_id'] = $product_param->product_temp_id;
                }else{
                    $result = $this->createResult('M08028',array());
                    return $result;
                }
                //获取默认作品
                $collection_id = DB::table('user_collections')->where([['user_id', '=', $input['user_id']], ['is_default', '=', 1]])->value('collection_id');
                if(empty($collection_id)){
                    $result = $this->createResult('M08003',(object)array());
                    return $result;
                }
                $insert_data['user_collection_id'] = $collection_id;
                $insert_data['is_shelves'] = 0;
                $insert_data['user_id'] = $input['user_id'];
                $insert_data['created_at'] = $insert_data['updated_at'] = time();
                $product_insert_flag = DB::table('products')->insert($insert_data);
                if(empty($product_insert_flag)){
                    $result = $this->createResult('M08028',(object)array());
                    return $result;
                }
                //保存product_id
                $product_print_detail_re = [];
                $return_result_detail['product_print_detail'] = [];
                $product_print_materials = array();
                foreach($product_param->product_print_detail as $print){
                    $product_print_materials_detail = array();
                    $product_print = DB::table('product_prints')
                        ->where('id',$print->product_print_id)
                        ->select('id','temp_id','colour_id','position_type','craftsmanship_name')
                        ->first();
                    if(empty($product_print) || $product_print->temp_id != $product_param->product_temp_id || $product_print->colour_id != $product_param->colour_id){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    $flag_product_prints = DB::table('product_prints')->where('id',$print->product_print_id)
                        ->update(['product_id'=>$product_id,'updated_at'=>time()]);
                    $flag_product_print_materials = DB::table('product_print_materials')->where('product_print_id',$product_print->id)->update(['product_id'=>$product_id,'updated_at'=>time()]);
                    if(empty($flag_product_prints) || empty($flag_product_print_materials)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //保存图片
                    //判断是否存在图片
                    $print->original_image = ImgTool::getImgPathByImgUrl($print->original_image);
                    $print->thumbnail = ImgTool::getImgPathByImgUrl($print->thumbnail);
                    if(empty($print->original_image) || !file_exists(public_path().self::PREFIX_PATH.$print->original_image)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    if(empty($print->thumbnail) || !file_exists(public_path().self::PREFIX_PATH.$print->thumbnail)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //Todo(缩略图与轮播图是一样)
                    //将图片转移
                    $old_file = public_path().self::PREFIX_PATH.$print->original_image;
                    //图片格式
                    $extension = '.'.$this->imagick_tool->getImageExt($old_file);
                    $prefix_name = md5(date('ymdhis').rand(1, 1000));
                    $child_folder = date('Ym',time());
                    $folder = public_path() .self::PREFIX_PATH.self::IMAGE_PATH.$child_folder;
                    $this->imagick_tool->mkFolder($folder);
                    $new_file = $folder.'/'.$prefix_name.$extension;
                    $output = shell_exec("mv ".$old_file." ".$new_file." &&  echo 'success'");
                    if(empty($output)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //判断图片唯一性
                    $md5_image = md5_file($new_file);
                    rename($new_file,$folder.'/'.$md5_image.$extension);
                    $real_path = ImgTool::saveImgToDbByImgPath(self::IMAGE_PATH.$child_folder.'/'.$md5_image.$extension);
                    //保存缩率图
                    $insert_preview_data = array(
                        'product_id' => $product_id,
                        'product_preview_original_image' => $real_path,
                        'product_preview_thumbnail_image' => $real_path,
                        'position_type' => $product_print->position_type,
                        'craftsmanship_name' => $product_print->craftsmanship_name,
                        'created_at' => time(),
                        'updated_at' => time()
                    );
                    $product_preview_image_id = DB::table('product_preview_images')->insertGetId($insert_preview_data);
                    if(empty($product_preview_image_id)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    $product_print_materials_ids = DB::table('product_print_materials')->where('product_print_id',$print->product_print_id)->pluck('id')->toArray();
                    $product_print_materials_detail['product_print_id'] = $product_print->id;
                    $product_print_materials_detail['product_print_materials_ids'] = $product_print_materials_ids;
                    $product_print_materials_detail['position_type'] = $product_print->position_type;
                    $product_print_materials_detail['product_preview_image_id'] = $product_preview_image_id;
                    $product_print_materials[] = $product_print_materials_detail;
                    $return_result_detail['original_image'][] = env('IMG_URL_STD_PREFIX').$real_path;
                    $return_result_detail['thumbnail'][] = env('IMG_URL_STD_PREFIX').$real_path;
                    $product_print_detail_re['product_print_id'] = $print->product_print_id;
                    $product_print_detail_re['original_image'] = $product_print_detail_re['thumbnail'] = env('IMG_URL_STD_PREFIX').$real_path;
                    $return_result_detail['product_print_detail'][] = $product_print_detail_re;
                }
                //计算产品价格
                $product = DB::table('products')->where('product_id',$product_id)->select('product_id','product_temp_id','colour_id','overflow_price')->first();
                $prices = $this->getTotalPrice($product);
                //更新价格
                if($prices['total_price'] != 0 || $prices['total_preferential_price'] != 0){
                    $product_price_flag = DB::table('products')->where('product_id',$product_id)->update(['price'=>$prices['total_price'],'preferential_price'=>$prices['total_preferential_price'],'updated_at'=>time()]);
                    if(empty($product_price_flag)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                }
                $print_param_details['product_id'] = $product_id;
                $print_param_details['product_print_materials'] = $product_print_materials;
                $print_param[] = $print_param_details;
                $product_ids[] = $product_id;

                $colour_name = ColourTool::getColourSimpleInfoByColourId(intval($product_param->colour_id));
                $colour = $colour_name === null ? (object)array() : $colour_name;
                $return_result_detail['colour'] = $colour;
                $return_result_detail['product_temp_id'] = $product_param->product_temp_id;
                $return_result_detail['product_draft_id'] = 0;
                $return_result_detail['original_price'] = GeneralTool::priceFormat($prices['total_price']);
                $return_result_detail['preferential_price'] = GeneralTool::priceFormat($prices['total_preferential_price']);
                $cost_detail_list = [];
                $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product_param->product_temp_id, $product_param->colour_id,0);
                $cost_detail_list[] = array(
                    'resource_id'=>$product_param->product_temp_id,
                    'title'=>$product_temp->brand_name.$product_temp->product_temp_name,
                    'preferential_price'=>GeneralTool::priceFormat($product_temp->preferential_price),
                    'original_price'=>GeneralTool::priceFormat($product_temp->original_price),
                    'thumbnail'=>$product_temp->thumbnail,
                    'quantity'=>1,
                    'type'=>1
                );
                $material_detail = $this->get_material_detail($product_id, $product_param->product_temp_id, 1);
                $customize_material_detail = $this->get_customiz_material_detail($product_id, 1);
                $font_detail = $this->get_font_detail($product_id, 1);
                $cost_detail_list = array_merge($cost_detail_list,$material_detail,$customize_material_detail,$font_detail);
                $return_result_detail['lists'] = $cost_detail_list;
                $return_result[] = $return_result_detail;

                //增加模板使用量
                ProductTempTool::increasedProdTempUsedNum($product_param->product_temp_id,1);
            }
            //删除草稿
            if(isset($input['product_draft_md5']) && !empty($input['product_draft_md5'])){
                $update_res = DB::table('product_drafts')
                  ->where(['md5'=>$input['product_draft_md5'],'user_id'=>$input['user_id'],'state'=>1]) 
                  ->update(['state'=>2,'updated_at'=>time()]);
                if(empty($update_res)){
                    $result = $this->createResult('M08028',(object)array());
                    return $result;
                }  
            }
            Log::info('-------------------普通用户图片打印开始begin---------------------------');
            dispatch(new Php2PyImg($print_param));
            Log::info('-------------------普通用户图片打印开始end---------------------------');
            $result = $this->createResult('M00000',array('product_id'=>$product_ids[0],'product_draft_md5'=>'','data'=>$return_result));
            return $result;
        }catch (\Exception $e){
            Log::info($e);
            DB::rollback();
            $result = $this->createResult('M08028',(object)array());
            return $result;
        }finally{
            if(empty($result) || $result['state'] != 'M00000'){
                DB::rollback();
            }
            DB::commit();
        }
    }

    /**
     * 草稿功能
     * @Author    zhouchao
     * @DateTime  2017-03-06
     * @copyright 2016 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [3.1.1]
     * @param     array $input   制作产品详细参数
     * @return    array
     */
    public function save_product_draft_preview($input)
    {
        //生成预览图
        $result = $this->products_create_service->create_product_preview($input);
        if ($result['state'] != 'M00000') {
            return $result;
        }
        //保存数据
        $md5 = md5(date('ymdhis') . rand(1, 10000) . $input['user_id']);
        $input = $result['result'];
        foreach ($input['product_templates'] as $product_temp_data) {
            //不同颜色
            if(isset($product_temp_data->product_draft_id)){
                DB::table('product_drafts')
                    ->where('product_draft_id',$product_temp_data->product_draft_id)
                    ->update(['state'=>2,'updated_at'=>time()]);
            }
            $product_draft_id = DB::table('product_drafts')->insertGetId([
                'user_id'         => $input['user_id'],
                'md5'             => $md5,
                'product_temp_id' => $product_temp_data->product_temp_id,
                'version'         => isset($product_temp_data->product_draft_id) ? $product_temp_data->product_draft_id : 0,
                'colour_id'       => $product_temp_data->colour_id,
                'state'           => 1,
                'created_at'      => time(),
                'updated_at'      => time()
            ]);
            foreach ($product_temp_data->creative_parameters as $creative_parameter) {
                //保存打印参数开始 (一个区域一条 一个作品多个区域)
                if(!empty($creative_parameter->image_parameters)){
                    $product_print_id = DB::table('product_prints')->insertGetId([
                        //'product_id' => $product_id,
                        'product_draft_id' => $product_draft_id,
                        'user_id' => $input['user_id'],
                        'temp_id' => $product_temp_data->product_temp_id,
                        'colour_id' => $product_temp_data->colour_id,
                        'style_box_w' => $creative_parameter->style_box_w,
                        'style_box_h' => $creative_parameter->style_box_h,
                        'sketchpad_width' => $input['sketchpad_width'],
                        'sketchpad_height' => $input['sketchpad_height'],
                        'position_type' => $creative_parameter->position_type,
                        'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                        'craftsmanship_type' => $creative_parameter->craftsmanship_type,
                        'app_version' => isset($input['app_version']) ? $input['app_version'] : '',
                        'state' => 1,
                        'created_at' => time(),
                        'updated_at' => time()
                    ]);
                    foreach ($creative_parameter->image_parameters as $image_parameter) {
                        if ($image_parameter->type == 1) {
                            //图片
                            $product_print_materials_id = DB::table('product_print_materials')->insertGetId([
                                'product_print_id' => $product_print_id,
                                'product_draft_id' => $product_draft_id,
                                'creative_id' => $image_parameter->creative_id,
                                'craftsmanship_type' => $creative_parameter->craftsmanship_type,
                                'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                                'image_finnal_size_width' => $image_parameter->image_finnal_size_width,
                                'image_finnal_size_height' => $image_parameter->image_finnal_size_height,
                                'mask_finnal_size_height' => isset($image_parameter->mask_finnal_size_height) ? $image_parameter->mask_finnal_size_height : 0,
                                'mask_finnal_size_width' => isset($image_parameter->mask_finnal_size_width) ? $image_parameter->mask_finnal_size_width : 0,
                                'mask_id' => isset($image_parameter->mask_id) ? $image_parameter->mask_id : 0,
                                'mask_center_point_offset_x' => isset($image_parameter->mask_center_point_offset_x) ? $image_parameter->mask_center_point_offset_x : 0,
                                'mask_center_point_offset_y' => isset($image_parameter->mask_center_point_offset_y) ? $image_parameter->mask_center_point_offset_y : 0,
                                'center_point_offset_x' => $image_parameter->image_center_point_offset_x,
                                'center_point_offset_y' => $image_parameter->image_center_point_offset_y,
                                'angle' => $image_parameter->image_angle,
                                'type' => $image_parameter->type,
                                'image_type' => $image_parameter->image_type,
                                'font_svg' => '',
                                'edit_view_level' => $image_parameter->edit_view_level,
                                'is_horizontal_filp' => $image_parameter->is_horizontal_filp,
                                'is_vertical_filp' => $image_parameter->is_vertical_filp,
                                'state' => 1,
                                'created_at' => time(),
                                'updated_at' => time()
                            ]);
                        } else {
                            $product_print_materials_id = DB::table('product_print_materials')->insertGetId([
                                'product_print_id' => $product_print_id,
                                'product_draft_id' => $product_draft_id,
                                'craftsmanship_type' => $creative_parameter->craftsmanship_type,
                                'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                                'center_point_offset_x' => $image_parameter->font_center_point_offset_x,
                                'center_point_offset_y' => $image_parameter->font_center_point_offset_y,
                                'angle' => $image_parameter->font_angle,
                                'type' => 2,
                                'edit_view_level' => $image_parameter->edit_view_level,
                                'text' => $image_parameter->text,
                                'font_id' => $image_parameter->font_id,
                                'font_size' => $image_parameter->font_size,
                                'font_color' => $image_parameter->font_color,
                                'font_alpha' => $image_parameter->font_alpha,
                                'font_svg' => isset($image_parameter->font_svg) ? json_encode($image_parameter->font_svg) : '',
                                'state' => 1,
                                'created_at' => time(),
                                'updated_at' => time()
                            ]);
                        }
                    }

                    //保存草稿预览图
                    //将图片转移
                    $old_file = public_path().self::PREFIX_PATH.$creative_parameter->image_path;
                    //图片格式
                    $extension = '.'.$this->imagick_tool->getImageExt($old_file);
                    $prefix_name = md5(date('ymdhis').rand(1, 1000));
                    $child_folder = date('Ym',time());
                    $folder = public_path() .self::PREFIX_PATH.self::DRAFT_IMAGE_PATH.$child_folder;
                    $this->imagick_tool->mkFolder($folder);
                    $new_file = $folder.'/'.$prefix_name.$extension;
                    $mv_output = shell_exec("mv ".$old_file." ".$new_file." &&  echo 'success'");
                    if(empty($mv_output)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                    //判断图片唯一性
                    $md5_image = md5_file($new_file);
                    rename($new_file,$folder.'/'.$md5_image.$extension);
                    $real_path = self::DRAFT_IMAGE_PATH.$child_folder.'/'.$md5_image.$extension;
                    //$real_path = ImgTool::saveImgToDbByImgPath(self::DRAFT_IMAGE_PATH.$child_folder.'/'.$md5_image.$extension);
                    //保存缩率图
                    $insert_preview_data = array(
                        'product_id' => '',
                        'product_draft_id' => $product_draft_id,
                        'product_preview_original_image' => $real_path,
                        'product_preview_thumbnail_image' => $real_path,
                        'position_type' => $creative_parameter->position_type,
                        'craftsmanship_name' => $creative_parameter->craftsmanship_name,
                        'created_at' => time(),
                        'updated_at' => time()
                    );
                    $product_preview_image_id = DB::table('product_preview_images')->insertGetId($insert_preview_data);
                    if(empty($product_preview_image_id)){
                        $result = $this->createResult('M08028',(object)array());
                        return $result;
                    }
                }
            }
        }
        //删除草稿
        if(isset($input['product_draft_md5']) && !empty($input['product_draft_md5'])){
            $update_res = DB::table('product_drafts')
                            ->where(['md5'=>$input['product_draft_md5'],'user_id'=>$input['user_id'],'state'=>1]) 
                            ->update(['state'=>2,'updated_at'=>time()]);
            if(empty($update_res)){
                $result = $this->createResult('M08028',(object)array());
                return $result;
            }  
        }
        return $this->createResult('M00000',(object)array());
    }

    /**
     * 获取草稿列表
     * @Author    zhouchao
     * @DateTime  2017-03-06
     * @copyright 2016 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     int $user_id 用户ID
     * @param     int $per_page 每页显示数量
     * @return    array
     */
    public function get_draft_list($user_id, $per_page)
    {
        $product_drafts = DB::table('product_drafts')
            ->where(['user_id'=>$user_id,'state'=>1])
            ->select('product_draft_id','colour_id','md5','product_temp_id','created_at')
            ->orderBy('created_at','desc')
            ->paginate($per_page)
            ->toArray();
        foreach($product_drafts['data'] as $product_draft){
            $previews = DB::table('product_preview_images')
                ->where(['product_draft_id'=>$product_draft->product_draft_id,'state'=>1])
                ->select('product_preview_original_image','product_preview_thumbnail_image')
                ->get();
            $product_draft->original_image = array();
            $product_draft->thumbnail = array();
            foreach ($previews as $preview) {
                $product_draft->original_image[] = ImgTool::getProductThumbImgCDNUrlByImgPath($preview->product_preview_original_image);
                $product_draft->thumbnail[] = ImgTool::getProductThumbImgCDNUrlByImgPath($preview->product_preview_thumbnail_image);
            }
            //获取模板信息
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product_draft->product_temp_id, $product_draft->colour_id,0);
            $product_draft->brand_name = empty($product_temp) ? '' : $product_temp->brand_name;
            $product_draft->product_temp_name = empty($product_temp) ? '' : $product_temp->product_temp_name;    
            $product_draft->product_temp_category_id = $this->product_temp_tool->getProductTempCategoryIdByProductTempId($product_draft->product_temp_id,1);
        }
        $result = array('total_page' => $product_drafts['last_page'], 'per_page' => $per_page, 'current_page' => $product_drafts['current_page'], 'data' => $product_drafts['data']);
        return $this->createResult('M00000', $result);
    }

    /**
     * 删除草稿
     * @Author    zhouchao
     * @DateTime  2017-03-06
     * @copyright 2016 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     int $user_id
     * @param     int $product_draft_id
     * @return    array
     */
    public function delete_draft($user_id, $product_draft_id)
    {
        $product_draft = DB::table('product_drafts')
            ->where(['user_id'=>$user_id,'product_draft_id'=>$product_draft_id,'state'=>1])
            ->first();
        if(empty($product_draft)){
            return $this->createResult('M08030', (object)array());
        }
        $result = DB::table('product_drafts')
            ->where(['user_id'=>$user_id,'product_draft_id'=>$product_draft_id,'state'=>1])
            ->update(['state'=>2,'updated_at'=>time()]);
        return empty($result) ? $this->createResult('M00001', (object)array(), 'globalcodes', '删除') : 
                                $this->createResult('M00000', (object)array(), 'globalcodes', '删除');       
    }

    /**
     * 草稿上架
     * @Author    zhouchao
     * @DateTime  2017-03-07
     * @copyright 2016 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     int $user_id          用户编号
     * @param     int $product_draft_id 草稿编号
     * @return    array
     */
    public function draft_shelves($user_id, $product_draft_id)
    {
        // 1 获取草稿
        $product_draft = DB::table('product_drafts')
            ->where(['user_id'=>$user_id,'product_draft_id'=>$product_draft_id,'state'=>1])
            ->select('product_draft_id','md5','product_temp_id','colour_id','created_at')
            ->first();
        if(empty($product_draft)){
            return $this->createResult('M08030', (object)array());
        }

        // 2 获取同款不同色的草稿
        $product_drafts = DB::table('product_drafts')
            ->where(['user_id'=>$user_id,'md5'=>$product_draft->md5,'state'=>1])
            ->where('product_draft_id','<>',$product_draft_id) 
            ->select('product_draft_id','md5','product_temp_id','colour_id','created_at')
            ->get()
            ->toArray();

        // 3 合并草稿       
        array_unshift($product_drafts, $product_draft); 

        // 4 循环获取草稿信息
        $output = [];
        $product_detail = [];
        foreach($product_drafts as $key=>$product_draft){
            //4-1 获取product_print_detail
            $product_print_detail = [];
            $original_image = [];
            $thumbnail = [];
            $cost_detail_list = [];
            $price = 0;//真实价格
            $preferential_price = 0;//优惠价格
            $product_prints = DB::table('product_prints')
                                ->where(['product_draft_id'=>$product_draft->product_draft_id,'state'=>1])
                                ->select('id as product_print_id','position_type')
                                ->get()
                                ->toArray();
            foreach($product_prints as $key=>$product_print){
                //4-2 根据product_draft_id和position_type获取预览图
                $preview = DB::table('product_preview_images')
                             ->where(['product_draft_id'=>$product_draft->product_draft_id,'position_type'=>$product_print->position_type,'state'=>1])
                             ->select('product_preview_original_image','product_preview_thumbnail_image')
                             ->first();
                $product_print_detail[$key]['product_print_id'] = $product_print->product_print_id;
                $product_print_detail[$key]['original_image'] = ImgTool::getProductThumbImgCDNUrlByImgPath($preview->product_preview_original_image);
                $product_print_detail[$key]['thumbnail'] = ImgTool::getProductThumbImgCDNUrlByImgPath($preview->product_preview_thumbnail_image);
                $original_image[] = ImgTool::getProductThumbImgCDNUrlByImgPath($preview->product_preview_original_image);
                $thumbnail[] = ImgTool::getProductThumbImgCDNUrlByImgPath($preview->product_preview_original_image);
            }
            
            //4-3 获取详情 
            $cost_detail_list = [];
            $product_temp = $this->product_temp_tool->getProdTempDetailByProdTempId($product_draft->product_temp_id, $product_draft->colour_id,0);
            $cost_detail_list[] = array(
                'resource_id'=>$product_draft->product_temp_id,
                'title'=>$product_temp->brand_name.$product_temp->product_temp_name,
                'preferential_price'=>GeneralTool::priceFormat($product_temp->preferential_price),
                'original_price'=>GeneralTool::priceFormat($product_temp->original_price),
                'thumbnail'=>$product_temp->thumbnail,
                'quantity'=>1,
                'type'=>1
            );
            $material_detail = $this->get_material_detail($product_draft->product_draft_id, $product_draft->product_temp_id);
            $customize_material_detail = $this->get_customiz_material_detail($product_draft->product_draft_id);
            $font_detail = $this->get_font_detail($product_draft->product_draft_id);
            $cost_detail_list = array_merge($cost_detail_list,$material_detail,$customize_material_detail,$font_detail);

            //4-4 获取颜色信息
            $colour_name = ColourTool::getColourSimpleInfoByColourId(intval($product_draft->colour_id));
            $colour = $colour_name === null ? (object)array() : $colour_name;

            //4-5 计算价格
            foreach($cost_detail_list as $key=>$value){
                $price = bcadd($price, $value['original_price'], 2);
                $preferential_price = bcadd($preferential_price, $value['preferential_price'], 2);
            }
            $product_detail['product_draft_id'] = $product_draft->product_draft_id;
            $product_detail['product_print_detail'] = $product_print_detail;
            $product_detail['original_image'] = $original_image;
            $product_detail['thumbnail'] = $thumbnail;
            $product_detail['original_price'] = GeneralTool::priceFormat($price);
            $product_detail['preferential_price'] = GeneralTool::priceFormat($preferential_price);
            $product_detail['product_temp_id'] = $product_draft->product_temp_id;
            $product_detail['colour'] = $colour;
            $product_detail['lists'] = $cost_detail_list;
            $output[] = $product_detail;
        }
        return $this->createResult('M00000', ['data'=>$output,'product_draft_md5'=>$product_draft->md5]);
    }

    /**
     * 草稿编辑
     * @Author    zhouchao
     * @DateTime  2017-03-07
     * @copyright 2016 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     int $user_id           用户ID
     * @param     int $product_draft_id  草稿ID
     * @return    array
     */
    public function draft_edit($user_id, $product_draft_id)
    {
        $product_draft = DB::table('product_drafts')
                           ->where(['user_id'=>$user_id,'product_draft_id'=>$product_draft_id,'state'=>1])
                           ->select('product_draft_id','md5','product_temp_id','colour_id','created_at')
                           ->first();
        if(empty($product_draft)){
            return $this->createResult('M08030', (object)array());
        }

        // 2 获取同款不同色的草稿
        $product_drafts = DB::table('product_drafts')
                            ->where(['user_id'=>$user_id,'md5'=>$product_draft->md5,'state'=>1])
                            ->where('product_draft_id','<>',$product_draft_id) 
                            ->select('product_draft_id','md5','product_temp_id','colour_id','created_at')
                            ->get()
                            ->toArray();

        // 3 合并草稿       
        array_unshift($product_drafts, $product_draft);
        $product_templates = [];
        foreach($product_drafts as $key=>$product_draft){
            $product_temp = [];
            $product_prints = DB::table('product_prints')
                                ->where(['product_draft_id'=>$product_draft->product_draft_id,'state'=>1])
                                ->select('id as product_print_id','position_type','craftsmanship_name','craftsmanship_type')
                                ->get()
                                ->toArray();
            $product_temp['colour_id'] = $product_draft->colour_id;
            $product_temp['product_draft_id'] = $product_draft->product_draft_id;
            $product_temp['product_temp_id'] = $product_draft->product_temp_id;
            //获取产品模板分类ID
            $product_temp['product_temp_category_id'] = $this->product_temp_tool->getProductTempCategoryIdByProductTempId($product_draft->product_temp_id,1);
            foreach($product_prints as $key=>$product_print){
                $product_temp['creative_parameters'][$key]['craftsmanship_name'] = $product_print->craftsmanship_name;
                $product_temp['creative_parameters'][$key]['craftsmanship_type'] = $product_print->craftsmanship_type;
                $product_temp['creative_parameters'][$key]['position_type'] = $product_print->position_type;
                $product_print_materials = DB::table('product_print_materials')
                                            ->where(['product_print_id'=>$product_print->product_print_id,'state'=>1])
                                            ->select('creative_id','image_finnal_size_width','image_finnal_size_height',
                                                     'mask_finnal_size_height','mask_finnal_size_width','mask_id',
                                                     'mask_center_point_offset_x','mask_center_point_offset_y',
                                                     'center_point_offset_x','center_point_offset_y','angle',
                                                     'type','image_type','edit_view_level','font_id','font_size','font_color',
                                                     'font_alpha','text','font_svg','is_horizontal_filp','is_vertical_filp')
                                            ->get()
                                            ->toArray();
                foreach($product_print_materials as $product_print_material){
                    if($product_print_material->font_svg == ''){
                        $product_print_material->font_svg = [];
                        $product_print_material->font_svg['text_svg_info'] = [];
                    }
                    if($product_print_material->type == 2){
                        //字体
                        $product_print_material->font_angle = $product_print_material->angle;
                        $product_print_material->font_center_point_offset_x = $product_print_material->center_point_offset_x;
                        $product_print_material->font_center_point_offset_y = $product_print_material->center_point_offset_y;
                        $product_print_material->font_svg = json_decode($product_print_material->font_svg);
                    }elseif($product_print_material->type == 1 && $product_print_material->image_type == 1){
                        //用户自定义素材
                        $product_print_material->image_angle = $product_print_material->angle;
                        $product_print_material->image_center_point_offset_x = $product_print_material->center_point_offset_x;
                        $product_print_material->image_center_point_offset_y = $product_print_material->center_point_offset_y;
                        $user_creative = DB::table('user_creatives')
                                           ->where(['creative_id'=>$product_print_material->creative_id,
                                                            'user_id'=>$user_id,'state'=>1])
                                           ->select('original_image','thumbnail')
                                           ->first(); 
                        $product_print_material->thumbnail = ImgTool::getProductThumbImgCDNUrlByImgPath($user_creative->thumbnail);                    
                    }else{
                        $product_print_material->image_angle = $product_print_material->angle;
                        $product_print_material->image_center_point_offset_x = $product_print_material->center_point_offset_x;
                        $product_print_material->image_center_point_offset_y = $product_print_material->center_point_offset_y;
                        //平台素材
                        $source_pic_result = $this->source_pic_tool->getSourcePicAvailableBySourcePicIdAndProdTempId($product_print_material->creative_id,$product_draft->product_temp_id,1);
                        if($source_pic_result['state'] != 'M00000'){
                            return $source_pic_result;
                        }
                        $product_print_material->thumbnail = ImgTool::getProductThumbImgCDNUrlByImgPath($source_pic_result['result']->thumbnail);
                    }
                    //蒙版信息
                    if(!empty($product_print_material->mask_id)){
                        //根据ID获取蒙版图片
                        $product_print_material->mask_url_path = DB::table('masks')->where(['mask_id'=>$product_print_material->mask_id,'state'=>1])->value('thumbnail');
                        if(empty($product_print_material->mask_url_path) || !is_file(public_path('images/').$product_print_material->mask_url_path)){
                            return $this->createResult('M08032',(object)array());
                        }
                        $product_print_material->mask_url_path = ImgTool::getProductThumbImgCDNUrlByImgPath($product_print_material->mask_url_path);
                    }else{
                        $product_print_material->mask_url_path = '';
                    }
                } 
                $product_temp['creative_parameters'][$key]['image_parameters'] = $product_print_materials;                
            } 
            $product_templates[] = $product_temp;                                     
        }
        return $this->createResult('M00000', ['data'=>$product_templates,'product_draft_md5'=>$product_draft->md5]);
    }

    /**
     * 获取系统素材详情
     * @Author    zhouchao
     * @DateTime  2017-03-07
     * @copyright 2016 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     int $resource_id   草稿编号或者作品ID
     * @param     string $product_temp_id 模板编号
     * @param     integer 0 草稿 1 作品 
     * @return    array
     */
    public function get_material_detail($resource_id,$product_temp_id,$type=0)
    {
        $source = array();
        //获取设计师或者品牌商素材价格
        if($type){
            $source_pic_ids = $this->getReSourceIds(
                array(
                    array('product_id', '=', $resource_id),
                    array('type', '=', 1), array('image_type', '=', 2),
                    array('state', '=', 1)
                ),
                'creative_id'
            );
        }else{
            $source_pic_ids = $this->getReSourceIds(
                array(
                    array('product_draft_id', '=', $resource_id),
                    array('type', '=', 1), array('image_type', '=', 2),
                    array('state', '=', 1)
                ),
                'creative_id'
            );
        }
        $source_pic_ids = array_unique($source_pic_ids);//获取所有素材ID
        foreach ($source_pic_ids as $source_pic_id) {
            //根据ID获取素材详情
            $source_pic_result = $this->source_pic_tool->getSourcePicAvailableBySourcePicIdAndProdTempId($source_pic_id,$product_temp_id,2);
            if($source_pic_result['state'] != 'M00000'){
                throw new ImageNotFoundException('素材ID为'.$source_pic_id.',素材类型为2的原图片未找到,原因:'.$source_pic_result['message']);
            }
            $prices = PreferentialService::getResourcePrice($source_pic_id, 1);
            if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                throw new PriceErrorException('ID为' . $source_pic_id . '的素材价格异常');
            }
//            $modify_price = ModifyResourcePriceRecordsService::is_resource_modify_price($source_pic_id,0,1);
            $source[] = array('resource_id'=>$source_pic_id,'title'=>$source_pic_result['result']->name,'preferential_price'=>GeneralTool::priceFormat($prices['preferential_price']),'original_price'=>GeneralTool::priceFormat($prices['original_price']),'thumbnail'=>env('IMG_URL_STD_PREFIX').$source_pic_result['result']->thumbnail,'quantity'=>1,'type'=>3);
        }
        return $source;
    }

    /**
     * 获取产品字体使用明细
     * @param $product_id
     * @param $product_temp_id
     */
    public function get_font_detail($resource_id,$type=0){
        $source = array();
        //计算字体价格
        if($type){
            $font_ids = $this->getReSourceIds(
                array(
                    array('product_id', '=', $resource_id),
                    array('type', '=', 2),
                    array('state', '=', 1)
                ),
                'font_id'
            );
        }else{
            $font_ids = $this->getReSourceIds(
                array(
                    array('product_draft_id', '=', $resource_id),
                    array('type', '=', 2),
                    array('state', '=', 1)
                ),
                'font_id'
            );
        }
        
        $font_ids = array_unique($font_ids);
        foreach ($font_ids as $font_id) {
            $font_path = DB::table('fonts')->where('font_id',$font_id)->value('font_path');
            $font_name = DB::table('fonts')->where('font_id',$font_id)->value('font_name');
            $font_image = DB::table('fonts')->where('font_id',$font_id)->value('font_image');
            if(empty($font_path) || !is_file(public_path('fonts/').$font_path)){
                throw new FontNotFoundException('地址为'.$font_path.'的字体未找到');
            }
            $prices = PreferentialService::getResourcePrice($font_id, 3);
            if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
                throw new PriceErrorException('ID为' . $font_id . '的字体价格异常');
            }
            $source[] = array('resource_id'=>$font_id,'title'=>$font_name,
                'preferential_price'=>GeneralTool::priceFormat($prices['preferential_price']),'original_price'=>GeneralTool::priceFormat($prices['original_price']),
                'thumbnail'=>env('IMG_URL_STD_PREFIX').$font_image,'quantity'=>1,'type'=>4);
        }
        return $source;
    }

    /**
     * 获取产品使用明细
     * @throws FontNotFoundException
     * @throws ImageNotFoundException
     * @throws PriceErrorException
     */
    public function get_customiz_material_detail($resource_id,$type=0)
    {
        $source = array();
        //获取自定义素材
        if($type){
            $source_pic_ids = $this->getReSourceIds(
                array(
                    array('product_id', '=', $resource_id),
                    array('type', '=', 1), array('image_type', '=', 1),
                    array('state', '=', 1)
                ),
                'creative_id'
            );
        }else{
            $source_pic_ids = $this->getReSourceIds(
                array(
                    array('product_draft_id', '=', $resource_id),
                    array('type', '=', 1), array('image_type', '=', 1),
                    array('state', '=', 1)
                ),
                'creative_id'
            );
        }
        $source_pic_ids = array_unique($source_pic_ids);
        foreach ($source_pic_ids as $source_pic_id) {
            //根据ID获取素材详情
            $this->setParameter([
                'table' => 'user_creatives',
                'where' => [['creative_id','=',$source_pic_id],['state','=',1]],
                'select'=> ['thumbnail','name','preferential_price','price as original_price']
            ]);
            $user_creatives = $this->getById();
            if(empty($user_creatives)){
                throw new ImageNotFoundException('素材ID为'.$source_pic_id.',素材类型为1的原图片未找到');
            }
            $source[] = array(
                'resource_id'=>$source_pic_id,
                'title'=>$user_creatives->name,
                'preferential_price'=>GeneralTool::priceFormat($user_creatives->preferential_price),
                'original_price'=>GeneralTool::priceFormat($user_creatives->original_price),
                'thumbnail'=>env('IMG_URL_STD_PREFIX').$user_creatives->thumbnail,
                'quantity'=>1,
                'type'=>2
            );
        }
        return $source;
    }
}
